require 'dbaccess.rb'
require 'rubygems'
require 'ruby-debug'
require 'time'

class Perf < DbAccess
  
  def initialize(hostname, username, password, dbname)
    super(hostname, username, password, dbname)
    @mycon = connect()
    @mycon.select_db(@dbname)
  end
  
  def close
    @mycon.close
  end
  
  def getprice(sym)
    
    sql = "SELECT tradeDate,close from historicalquote where symbol=\"#{sym}\";"
    res = @mycon.query(sql)
    
    return(res)
      
  end
  
  def getpriceinrange(sym, startdate, enddate)
    
    sql = "SELECT tradeDate,close from historicalquote where symbol=\"#{sym}\" 
      and tradeDate>=\"#{startdate}\" and tradeDate<=\"#{enddate}\";"
    res = @mycon.query(sql)

    return(res)

  end
  
  def getaveragepriceinrange(sym, startdate, enddate)
    
    res = getpriceinrange(sym, startdate, enddate)
    rec = []
    res.each_hash do |row|
      rec << row["close"].to_f
    end
    
    if (rec.size == 0) then
      puts "Warning, no points in record"
      themean = nil
    else
      themean = rec.inject{ |sum, el| sum + el }.to_f / rec.size
    end
    
    return(themean)
    
  end
  
  def getstartendpoints(thedate, width)
    
    sd = thedate - width.to_f / 2.0
    sdstr = "#{sd.year}-#{sd.month}-#{sd.day}"
    ed = thedate + width.to_f / 2.0
    edstr = "#{ed.year}-#{ed.month}-#{ed.day}"
    res = Hash.new()
    res["startdate"] = sdstr
    res["enddate"] = edstr
    return(res)
      
  end
  
  def computeperf(sym, deltat, width)
    
    ed = Date.today
    edres = getstartendpoints(ed, width)
    sd = ed - deltat
    sdres = getstartendpoints(sd, width)
    sdprice = getaveragepriceinrange(sym, sdres["startdate"], sdres["enddate"])
    edprice = getaveragepriceinrange(sym, edres["startdate"], edres["enddate"])
      
    if (sdprice != nil && edprice != nil)
      result = (edprice - sdprice) / sdprice * 100.0
    else
      result = nil
    end
    
    return(result)
    
  end

  
  def computeandstoreperf(sym, deltat)
   
    width = 10.0
    value = computeperf(sym, deltat, width)
    if (value == nil) then
      value = "NULL"
    end
    
    sql = "REPLACE INTO perf (`symbol`, `last_trade_date`, `value`, `timed`) 
      VALUES('#{sym}', '#{Date.today.to_s}', #{value}, #{deltat});"
    @mycon.query(sql)
    
  end
  
  def generateperf(exchange)

    res = @mycon.query("select * from symbols where exchange = \"#{exchange}\"")
    res.each do |result|
   
      symbol = result[0].to_s
      puts "Processing Symbol #{symbol}..."
      computeandstoreperf(symbol, 10.0)
      #computeandstoreperf(symbol, 180.0)
      #computeandstoreperf(symbol, 270.0)
      #computeandstoreperf(symbol, 365.0)
      
    end
    
  end
 
end
